package cn.dd.crmweb.modules.sys.controller;

import cn.dd.crmweb.common.Result;
import cn.dd.crmweb.common.constans.Constans;
import cn.dd.crmweb.modules.sys.dto.UserDto;
import cn.dd.crmweb.modules.sys.entity.User;
import cn.dd.crmweb.modules.sys.mapper.UserMapper;
import cn.dd.crmweb.modules.sys.service.IUserService;
import cn.dd.crmweb.utils.TokenUtils;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

@RequestMapping("/sys/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

    //查询所有
    @GetMapping("/list")
    public List<User> findAll(){
        return userService.list();
    }

    //根据id查询
    @GetMapping("/{username}")
    public Result findName(@PathVariable("username") String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
//        queryWrapper.eq("id",id)
        return Result.success(userService.getOne(queryWrapper));
    }

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constans.CODE_400,"参数错误");
        }
        UserDto dto = userService.login(userDto);

        return  Result.success(dto);
    }

    //注册
    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto){
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constans.CODE_400,"参数错误");
        }
        return  Result.success(userService.register(userDto));
    }
    //新增或修改

    @PostMapping("/add")
    public boolean save(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }


    @DeleteMapping("{id}/delete")
    public boolean delete(@PathVariable("id") String id ) {
        return userService.removeById(id);
    }

    @DeleteMapping ("batch/delete")
    public boolean deleteBatch(@RequestBody List<String> ids){
        return userService.removeByIds(ids);
    }


}
